<template>
    <el-card>
        <template #header>
            <div class="card-header">
                <span>发布文章</span>
            </div>
        </template>
        <el-form ref="formRef" :rules="rules" :model="form">
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" />
            </el-form-item>
            <el-form-item label="描述" prop="textarea">
                <el-input v-model="form.textarea" :rows="2" type="textarea"  />
            </el-form-item>
            <el-form-item class="cate" label="分类"  prop="cate_1st">
                <el-space>
                    <el-select v-model="form.cate_1st" class="m-2" placeholder="Select">
                        <el-option v-for="item in options_1st" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                    <el-space>
                    <el-select v-model="form.cate_2nd" class="m-2" placeholder="Select" >
                        <el-option v-for="item in options_2nd" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-space>
                </el-space>
            </el-form-item>
            <el-form-item label="主图" prop="picture">
                <el-upload action="#" list-type="picture-card" :auto-upload="false">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="内容">
                <div style="border: 1px solid #ccc">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" />
                    <Editor style="height: 500px; overflow-y: hidden;" v-model="form.content"
                        :defaultConfig="editorConfig" @onCreated="handleCreated" />
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleRelease(formRef)">发布文章</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>


<script setup>
    import Category from '@/api/category';
import Notice from '@/api/notice';
// 引入 css
import '@wangeditor/editor/dist/css/style.css';
import { ref,reactive,onBeforeUnmount, shallowRef,onMounted,watch } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
//获取vue实例对象(跳转页面)
import { useRouter } from 'vue-router';
//获取router实例对象
let router = useRouter();

//富文本编辑框:
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// //提取token
// let token = sessionStorage.token;
// let headers = { Authorization: `Bearer ${token}` };
const toolbarConfig = {};
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
};
//上传图片
editorConfig.MENU_CONF['uploadImage'] = {
    fieldName: 'file',
    server: 'http://localhost:3001/upload/editor/',
    // 自定义增加 http  header
    headers: {
        Authorization: `Bearer ${sessionStorage.token}`,
    },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
});
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
    editorRef.value = editor
};
//表单
const form = reactive({
    title: '',
    content: '',
    cate_1st:'',
   cate_2nd:'',
   textarea:''
});
//表单验证：
//获取form组件实例---校验登录
const formRef = ref();
//校验表单：
const rules = reactive({
    title: [
        { required: true, message: '请输入内容！', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入标题!', trigger: 'blur' },
        { min: 1, max: 50, message: '标题长度要求在5-50之间！', trigger: 'blur' }
    ],
    textarea:[
        { required: true, message: '请输入标题!', trigger: 'blur' },
        { min: 1, max: 50, message: '标题长度要求在5-50之间！', trigger: 'blur' }
    ],
    cate_1st: [
        { required: true, message: '必选项', trigger: 'change'  }
    ],
});

//发布按钮：
let handleRelease = (formEl) => {
    formEl.validate(async (valid, fields) => {
        //校验成功
        if (valid) {
            const { status, msg } = await Notice.release({ ...form });
            if (status) {
                //修改成功
                ElMessage.success(msg);
                // 跳转页面
                router.push('/notice/list');
            } else {
                ElMessage.error(msg);
            }
        } else {
            //未通过校验
            console.log('校验失败(字段)', fields);
            //注册失败
            ElMessage.error("校验未通过，发布公告失败！");
        }
    })
}
//1、获取两级分类：先获取一级分类，然后watch监听，得到二级分类
//一级分类列表
let options_1st = ref([]);
//二级分类列表
let options_2nd = ref([]);
//请求子集分类
let loadSubcate = async (id) => {
    let { status, data } = await Category.subcate({ id });
    if (status) {
        return data;
    }
}
onMounted(async () => {
    options_1st.value = await loadSubcate(0);
});
//watch监听一级分类，得到二级分类 
watch(() => form.cate_1st, async (newValue) => {
    options_2nd.value = await loadSubcate(newValue);
    form.cate_2nd =options_2nd.value[0].name;

});
</script>
<!-- <style>
    .cate{
        display: inline-block;
    }
    .el-form-item.cate{
        display: inline-block;
        width: 200px;
    }
</style> -->